//
//  TMCutterLayer.m
//  cutter
//
//  Created by mac on 15/12/8.
//  Copyright © 2015年 e360. All rights reserved.
//
#import "TMCutterLayer.h"
#import <CommonCrypto/CommonDigest.h>
#import <CommonCrypto/CommonCrypto.h>

@interface TMCutterLayer ()
@property(nonatomic, assign) TMCutterLayerType type;
@property(nonatomic, retain) NSMutableDictionary *attribute;
@end
@implementation TMCutterLayer
+(NSMutableDictionary*)property{
    static dispatch_once_t onceToken = 0;
    static NSMutableDictionary *instance = nil;
    dispatch_once(&onceToken, ^{
        instance = [[NSMutableDictionary alloc] init];
    });
    return instance;
}
+(instancetype)layer:(NSDictionary*)data{
    TMCutterLayer *temp = [[TMCutterLayer alloc] init];
    [temp setData:data];
    return temp;
}
-(instancetype)init{
    self = [super init];
    if (self) {
        [self setMultipleTouchEnabled:YES];
        [self setAttribute:[NSMutableDictionary dictionary]];
        [self setBackgroundColor:[UIColor clearColor]];
        [self setEnabled:YES];
        [self setScaleX:1];
        [self setScaleY:1];
        [self setScaleZ:1];
    }
    return self;
}
-(void)layoutSubviews{
    [super layoutSubviews];
    [self updateTransform];
    [self updateBounds];
}
-(void)updateBounds{
}
-(void)updateTransform{
    CATransform3D transform = CATransform3DIdentity;
    transform = CATransform3DTranslate(transform, self.x, self.y, self.z);
    transform = CATransform3DRotate(transform, self.rotationZ, 0, 0, 1);
    transform = CATransform3DRotate(transform, self.rotationY, 0, 1, 0);
    transform = CATransform3DRotate(transform, self.rotationX, 1, 0, 0);
    transform = CATransform3DScale(transform, self.scaleX, self.scaleY, self.scaleZ);
    //透视
    CATransform3D perspect = CATransform3DIdentity;
    perspect.m34 = -1.0f / 400;
    perspect = CATransform3DConcat(CATransform3DMakeTranslation(-self.x, -self.y, 0), perspect);
    perspect = CATransform3DConcat(perspect, CATransform3DMakeTranslation(+self.x, +self.y, 0));
    //
    [self.layer setTransform:CATransform3DConcat(transform, perspect)];
}
-(void)setData:(NSDictionary *)data{
    [self setAttribute:[NSMutableDictionary dictionary]];
    if (data != nil) {
        [self setIdentifier:[data valueForKey:TMCutterAttributeIdentifier]];
        [self setAlpha:[[data valueForKey:TMCutterAttributeAlpha] floatValue]];
        [self setColor:[[data valueForKey:TMCutterAttributeColor] integerValue]];
        [self setEnabled:[[data valueForKey:TMCutterAttributeEnabled] boolValue]];
        [self setRotationX:[[data valueForKey:TMCutterAttributeRotationX] floatValue]];
        [self setRotationY:[[data valueForKey:TMCutterAttributeRotationY] floatValue]];
        [self setRotationZ:[[data valueForKey:TMCutterAttributeRotationZ] floatValue]];
        [self setScaleX:[[data valueForKey:TMCutterAttributeScaleX] floatValue]];
        [self setScaleY:[[data valueForKey:TMCutterAttributeScaleY] floatValue]];
        [self setScaleZ:[[data valueForKey:TMCutterAttributeScaleZ] floatValue]];
        [self setX:[[data valueForKey:TMCutterAttributeX] floatValue]];
        [self setY:[[data valueForKey:TMCutterAttributeY] floatValue]];
        [self setZ:[[data valueForKey:TMCutterAttributeZ] floatValue]];
        [self updateTransform];
    }
}
-(NSDictionary *)data{
    NSMutableDictionary *temp = [NSMutableDictionary dictionary];
    [temp setValue:[NSNumber numberWithInteger:self.type] forKey:TMCutterAttributeType];
    [temp setValue:[NSNumber numberWithFloat:self.alpha] forKey:TMCutterAttributeAlpha];
    [temp setValue:[NSNumber numberWithInteger:self.color] forKey:TMCutterAttributeColor];
    [temp setValue:[NSNumber numberWithBool:self.enabled] forKey:TMCutterAttributeEnabled];
    [temp setValue:[NSNumber numberWithFloat:self.rotationX] forKey:TMCutterAttributeRotationX];
    [temp setValue:[NSNumber numberWithFloat:self.rotationY] forKey:TMCutterAttributeRotationY];
    [temp setValue:[NSNumber numberWithFloat:self.rotationZ] forKey:TMCutterAttributeRotationZ];
    [temp setValue:[NSNumber numberWithFloat:self.scaleX] forKey:TMCutterAttributeScaleX];
    [temp setValue:[NSNumber numberWithFloat:self.scaleY] forKey:TMCutterAttributeScaleY];
    [temp setValue:[NSNumber numberWithFloat:self.scaleZ] forKey:TMCutterAttributeScaleZ];
    [temp setValue:[NSNumber numberWithFloat:self.x] forKey:TMCutterAttributeX];
    [temp setValue:[NSNumber numberWithFloat:self.y] forKey:TMCutterAttributeY];
    [temp setValue:[NSNumber numberWithFloat:self.z] forKey:TMCutterAttributeZ];
    [temp setValue:self.identifier forKey:TMCutterAttributeIdentifier];
    return [NSDictionary dictionaryWithDictionary:temp];
}
//
-(void)setColor:(NSInteger)color{
    [self.attribute setValue:[NSNumber numberWithInteger:color] forKey:TMCutterAttributeColor];
    [self setNeedsDisplay];
}
-(NSInteger)color{
    return [[self.attribute valueForKey:TMCutterAttributeColor] integerValue];
}
-(UIColor*)colorWithHex:(NSInteger)color{
    CGFloat bc=(color & 0xFF);
    CGFloat gc=(color & 0xFF00) >> 8;
    CGFloat rc=(color & 0xFF0000) >> 16;
    return [UIColor colorWithRed:rc / 255.0 green:gc / 255.0 blue:bc / 255.0 alpha:1.0];
}
@end

//文本
@implementation TMCutterLabel
+(instancetype)layer:(NSDictionary*)data{
    TMCutterLabel *temp = [[TMCutterLabel alloc] init];
    [temp setType:MatchLayerTypeLabel];
    [temp setData:data];
    return temp;
}
-(void)drawRect:(CGRect)rect{
    if (self.text) {
        NSDictionary *attributes = @{NSFontAttributeName:[self convertFont], NSForegroundColorAttributeName:[self colorWithHex:self.color]};
        [self.text drawInRect:rect withAttributes:attributes];
    }
}
-(void)updateBounds{
    if (self.text) {
        CGSize size = [self.text sizeWithAttributes:@{NSFontAttributeName:[self convertFont]}];
        [self setBounds:CGRectIntegral(CGRectMake(0, 0, size.width, size.height))];
    }else{
        [self setBounds:CGRectZero];
    }
    //
    [self setNeedsDisplay];
    if ([self.delegate respondsToSelector:@selector(cutterLayerResize:)]) {
        [self.delegate cutterLayerResize:self];
    }
}
-(void)setData:(NSDictionary *)data{
    if (data != nil) {
        [super setData:data];
        [self setSize:[[data valueForKey:TMCutterAttributeSize] floatValue]];
        [self setText:[data valueForKey:TMCutterAttributeText]];
        [self setFont:[data valueForKey:TMCutterAttributeFont]];
    }
}
-(NSDictionary *)data{
    NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:[super data]];
    [temp setValue:[NSNumber numberWithFloat:self.size] forKey:TMCutterAttributeSize];
    [temp setValue:self.text forKey:TMCutterAttributeText];
    [temp setValue:self.font forKey:TMCutterAttributeFont];
    return temp;
}
-(UIFont*)convertFont{
    if (self.size == 0) {
        [self setSize:24];
    }
    if (self.font == nil) {
        [self setFont:@"Helvetica"];
    }
    return [UIFont fontWithName:self.font size:self.size];
}
//
-(void)setSize:(CGFloat)size{
    [self.attribute setValue:[NSNumber numberWithFloat:size] forKey:TMCutterAttributeSize];
    [self updateBounds];
}
-(CGFloat)size{
    return [[self.attribute valueForKey:TMCutterAttributeSize] floatValue];
}
-(void)setText:(NSString *)text{
    [self.attribute setValue:text forKey:TMCutterAttributeText];
    [self updateBounds];
}
-(NSString *)text{
    return [self.attribute valueForKey:TMCutterAttributeText];
}
-(void)setFont:(NSString *)font{
    [self.attribute setValue:font forKey:TMCutterAttributeFont];
    [self updateBounds];
}
-(NSString *)font{
    return [self.attribute valueForKey:TMCutterAttributeFont];
}
@end

//图像
@implementation TMCutterImage
+(instancetype)layer:(NSDictionary*)data{
    TMCutterImage *temp = [[TMCutterImage alloc] init];
    [temp setType:MatchLayerTypeImage];
    [temp setData:data];
    return temp;
}
-(void)drawRect:(CGRect)rect{
    if (self.bitmap) {
        [self.bitmap drawInRect:rect];
    }else{
        if (self.source) {
            [self.source drawInRect:rect];
        }
    }
}
-(void)updateBounds{
    if (self.source) {
        [self setBounds:CGRectIntegral(CGRectMake(0, 0, self.source.size.width, self.source.size.height))];
        //生成新图像
        if (self.bitmap == nil && self.color > 0) {
            CGRect rect = self.bounds;
            UIColor *color = [self colorWithHex:self.color];
            UIGraphicsBeginImageContextWithOptions(rect.size, NO, self.source.scale);
            CGContextSetFillColorWithColor(UIGraphicsGetCurrentContext(), color.CGColor);
            //
            UIRectFill(rect);
            [self.source drawInRect:rect blendMode:kCGBlendModeOverlay alpha:1.0f];
            [self.source drawInRect:rect blendMode:kCGBlendModeDestinationIn alpha:1.0f];
            [self setBitmap:UIGraphicsGetImageFromCurrentImageContext()];
            UIGraphicsEndImageContext();
        }
    }else{
        [self setBounds:CGRectZero];
    }
    //
    [self setNeedsDisplay];
    if ([self.delegate respondsToSelector:@selector(cutterLayerResize:)]) {
        [self.delegate cutterLayerResize:self];
    }
}
-(NSString *)cacheFile:(NSString*)file{
    NSString *caches = [NSHomeDirectory() stringByAppendingPathComponent:@"Library"];
    return [caches stringByAppendingPathComponent:[NSString stringWithFormat:@"%@",file]];
}
//
-(void)setData:(NSDictionary *)data{
    if (data != nil) {
        [super setData:data];
        [self setImage:[data valueForKey:TMCutterAttributeImage]];
    }
}
-(NSDictionary *)data{
    NSMutableDictionary *temp = [NSMutableDictionary dictionaryWithDictionary:[super data]];
    if (self.image) {
        [temp setValue:self.image forKey:TMCutterAttributeImage];
    }
    return temp;
}
//
-(void)setBitmap:(UIImage *)bitmap{
    [self.attribute setValue:bitmap forKey:TMCutterAttributeBitmap];
}
-(UIImage *)bitmap{
    return [self.attribute valueForKey:TMCutterAttributeBitmap];
}
-(void)setSource:(UIImage *)source{
    [self.attribute setValue:source forKey:TMCutterAttributeSource];
    [self setBitmap:nil];
    [self updateBounds];
}
-(UIImage *)source{
    return [self.attribute valueForKey:TMCutterAttributeSource];
}
-(void)setImage:(NSString *)image{
    [self.attribute setValue:image forKey:TMCutterAttributeImage];
    //
    __weak TMCutterImage *blockSelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        NSString *file = [blockSelf cacheFile:image];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        if ([fileManager fileExistsAtPath:file] == NO) {
            NSString *basePath = [[TMCutterLayer property] objectForKey:@"basePath"];
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@", basePath==nil ? @"" : basePath, image]];
            if (url) {
                NSString *dir = [file stringByDeletingLastPathComponent];
                if ([fileManager fileExistsAtPath:dir] == NO) {
                    [fileManager createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:nil];
                }
                //
                NSData *data = [NSData dataWithContentsOfURL:url];
                [data writeToFile:file atomically:YES];
            }
        }
        //
        NSData *data = [NSData dataWithContentsOfFile:file];
        UIImage *image = [UIImage imageWithData:data];
        dispatch_async(dispatch_get_main_queue(), ^{
            [blockSelf setSource:image];
        });
    });
}
-(NSString *)image{
    return [self.attribute valueForKey:TMCutterAttributeImage];
}
@end